package com.company;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 1. 生成编码为UTF-8的文件，包含汉字、字母和数字，用GBK编码读取第一步生成的文件
 * 2. 生成编码为GBK的文件，包含汉字、字母和数字，用UTF-8编码读取第一步生成的文件
 *
 * @date : 2023-06-14 上午9:41
 */

@Slf4j
public class P057_CheckFileEncoding {

    public static void main(String[] args) {
        useGbkReadUtf8();
        System.out.println();
        useUtf8ReadGBK();
    }

    private static void useGbkReadUtf8() {
        System.out.println("使用GBK编码读取UTF-8编码生成的文件");
        List<String> stringList = new ArrayList<>();
        stringList.add("我也有123一个梦想456gbk");
        stringList.add("890abc人类群星闪耀时xyz");

        String filename = "./file/new.txt";
        String encoding = "UTF-8";
        createTxt(stringList, filename, encoding);

        encoding = "GBK";
        List<String> list = readFile(filename, encoding);
        for (String s : list) {
            System.out.println(s);
        }
    }

    private static void useUtf8ReadGBK() {
        System.out.println("使用UTF-8编码读取GBK编码生成的文件");
        List<String> stringList = new ArrayList<>();
        stringList.add("我也有123一个梦想456gbk");
        stringList.add("890abc人类群星闪耀时xyz");

        String filename = "./file/new.txt";
        String encoding = "GBK";
        createTxt(stringList, filename, encoding);

        encoding = "UTF-8";
        List<String> list = readFile(filename, encoding);
        for (String s : list) {
            System.out.println(s);
        }
    }

    private static List<String> readFile(String filename, String encoding) {
        List<String> ans = new ArrayList<>();
        try (BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream(filename), encoding))) {
            String line;
            while ((line = buf.readLine()) != null) {
                ans.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ans;
    }

    private static void createTxt(List<String> list, String filename, String encoding) {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(filename), encoding))) {
            for (String s : list) {
                bw.write(s);
                bw.newLine();
                bw.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
